#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    int width = 300;
    int height = 400;

    //设置主题
    backGroundColor = QColor("#15559a");
    fontColor = QColor("#fff");
    startFontColor = QColor("#fff080");

    this->resize(width,height);

    title = "便签大师";
    ui->label_2->setText("版本：1.6.4");
    ui->label_2->setContentsMargins(20,0,0,0);
    this->setWindowTitle(title);

    model = new QStandardItemModel(this);
    ui->treeView->header()->hide();
    ui->treeView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    //禁止编辑
    ui->treeView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    //设置右键策略
    ui->treeView->setContextMenuPolicy(Qt::CustomContextMenu);
    //初始化treeview数据
    this->hashInit();


    connect(ui->treeView, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(on_treeView_customContextMenuRequested(const QPoint &)));
    this->setTrayIcon();

    // 计算窗口位置以使其位于屏幕右侧
    int screenWidth = QApplication::primaryScreen()->geometry().width();
    int screeHeight = QApplication::primaryScreen()->geometry().height();
    int windowWidth = this->geometry().width();
    int x = screenWidth - windowWidth;
    int y = - screeHeight; // 可以设置窗口在屏幕顶部的位置，或者根据需要调整

    // 设置窗口位置和大小
    this->move(x,y);



}


/**
 * hash 结构体初始化数据
**/
void MainWindow::hashInit(){
    //清空模型数据
    model->clear();
    hashNotes.clear(); //结构体hash
    qindex.clear(); //模型索引
    //ui->treeView->setStyleSheet("QTreeView::item { border-bottom: 1px solid gray; }");

    QColor backcolor;
    QColor foregcolor;
    NoteT noteText;
    // 创建 notes 对象
    QDir dir;
    // 尝试创建目录
    if (!dir.exists(rootpath)) dir.mkpath(rootpath);
    if(!hashNotes.contains("_nt_")){
        NoteT nt;
        nt.name = "_nt_";
        nt.backGroundColor = backGroundColor.name();
        nt.fontColor = fontColor.name();
        nt.startFontColor = startFontColor.name();
        hashNotes.insert("_nt_",nt);
    }

    QFileInfo fileInfo(dataFile);
    if (fileInfo.exists()){
        // 从文件加载 notes
        tt->loadHashFromFile(hashNotes,noteText,dataFile);
    }else{
        //初始化主题
        this->initBackForeg();
        return ;
    }

    // 添加根节点
    QStandardItem *rootNode = new QStandardItem(title);
    model->appendRow(rootNode);
    ui->treeView->setModel(model);
    QStandardItem *current = new QStandardItem("当前事项");

    // 使用迭代器遍历 QHash
    for (auto i = hashNotes.begin(); i != hashNotes.end(); ++i) {
        if(i.value().name == "_nt_"){
            backGroundColor = hashNotes.value("_nt_").backGroundColor;
            fontColor = hashNotes.value("_nt_").fontColor;
            startFontColor = hashNotes.value("_nt_").startFontColor;
            continue;
        }
        QString year = i.value().year;
        QString month = i.value().month;
        QString nfile = year + month;
        if(!qindex.value(year)){
            QStandardItem *yearNode = new QStandardItem(year);
            qindex.insert(year,yearNode);
            rootNode->appendRow(yearNode);
        }
        if(!qindex.value(nfile)){
            QStandardItem *monthNode = new QStandardItem(i.value().month);
            qindex.insert(nfile,monthNode);
            qindex.value(year)->appendRow(monthNode);
        }
        QString fileNodeName = i.value().name;
        QStandardItem *fileNode = new QStandardItem(fileNodeName);
        // 为每个项目设置背景色
        backcolor = i.value().backGroundColor;
        foregcolor = i.value().fontColor;
        QBrush brush(backcolor); // 创建一个 QBrush 对象并设置颜色
        QVariant backgroundVariant(brush); // 将 QBrush 包装在 QVariant 中

        //星标颜色
        //QBrush redfBrush(Qt::red); // 创建一个 QBrush 对象并设置颜色
        //QBrush redbBrush(Qt::black);; // 创建一个 QBrush 对象并设置颜色
        QVariant redforegcolor(startFontColor); // 将 QBrush 包装在 QVariant 中
        //QVariant redbackcolor(redbBrush); // 将 QBrush 包装在 QVariant 中
        // 为每个项目设置前景色
        QBrush frush(foregcolor); // 创建一个 QBrush 对象并设置颜色
        QVariant ForegroundVariant(frush); // 将 QBrush 包装在 QVariant 中
        fileNode->setData(backgroundVariant, Qt::BackgroundRole); // 设置背景色
        fileNode->setData(ForegroundVariant, Qt::ForegroundRole); // 设置


        qindex.insert(i.value().name,fileNode);
        //当前事项
        if(i.value().status == "false"){
            if(i.value().priority == "red"){
                fileNode = new QStandardItem("★ " + i.value().name);
                fileNode->setData(backgroundVariant, Qt::BackgroundRole); // 设置背景色
                fileNode->setData(redforegcolor, Qt::ForegroundRole); // 设置
                current->insertRow(0,fileNode);
            }else{
                current->appendRow(fileNode);
            }
            continue;
        }
        //归档事项
        if(i.value().priority == "red"){
            fileNode = new QStandardItem("★ " + i.value().name);
            fileNode->setData(backgroundVariant, Qt::BackgroundRole); // 设置背景色
            fileNode->setData(redforegcolor, Qt::ForegroundRole); // 设置
            qindex.value(nfile)->insertRow(0,fileNode);
        }else{
            qindex.value(nfile)->appendRow(fileNode);
        }
    }
    rootNode->appendRow(current);
    ui->treeView->setExpanded(rootNode->index(),true);
    ui->treeView->setExpanded(current->index(),true);
    //初始化主题
    this->initBackForeg();
}

// 保存 notes 到文件
void MainWindow::saveHash(){
    tt->saveHashToFile(dataFile, hashNotes);
}

/**
 * 初始化主题
**/
void MainWindow::initBackForeg(){

    this->setStyleSheet("background-color:"+ backGroundColor.name() +
                        "; color: "+ fontColor.name() +";");
}

void MainWindow::on_treeView_customContextMenuRequested(const QPoint &pos){
    QModelIndex index = ui->treeView->indexAt(pos);
    if (index.isValid()) {
        QMenu *menu = new QMenu(this);
        QAction *del = menu->addAction("删除");
        QAction *red = menu->addAction("★ 紧急");
        QAction *green = menu->addAction("一般");
        QAction *complete = menu->addAction("完成");
        QAction *todo = menu->addAction("未完成");

        // ... 添加更多操作
        QAction *selectedAction = menu->exec(ui->treeView->viewport()->mapToGlobal(pos));
        QString filePath = model->itemFromIndex(index)->text();
        if(filePath.left(2) == "★ ") filePath.remove(0,2);
        if(selectedAction == del){
            hashNotes.remove(filePath);
            if(!hashNotes["_nt_"].status.contains("删除文件" + filePath)){
                hashNotes["_nt_"].status += " 删除文件" + filePath;
            }
        }else if(selectedAction == red){
            hashNotes[filePath].priority = "red";
        }else if(selectedAction == green){
            hashNotes[filePath].priority = "green";
        }else if(selectedAction == complete){
            hashNotes[filePath].status = "true";
        }else if(selectedAction == todo){
            hashNotes[filePath].status = "false";
        }

        this->saveHash();
        this->hashInit();
    }
}


MainWindow::~MainWindow()
{
    delete ui;
}

/**
 * 双击便签标题打开便签
**/
void MainWindow::on_treeView_doubleClicked(const QModelIndex &index)
{

    QString fileName = model->itemFromIndex(index)->text();
    if(fileName.left(2) == "★ ") fileName.remove(0,2);
    if(hashNotes.value(fileName).name.isEmpty())return;
    notes *n = new notes(fileName,&hashNotes,this);
    n->show();// 使用 show()显示非模态窗口 而不是 exec()
    connect(n,&notes::sigClose,this,&MainWindow::sigClose);
}

/**
 * 新建便签
**/
void MainWindow::on_pushButton_clicked()
{
    QDate date = QDate::currentDate();
    NoteT ntt;
    ntt.name = date.toString("yyyy-MM-dd");
    ntt.year = date.toString("yyyy");
    ntt.month = date.toString("MM");
    ntt.priority = "green";
    ntt.status = "false";
    ntt.backGroundColor = this->backGroundColor.name();
    ntt.fontColor = this->fontColor.name();
    nt->insert(ntt.name,ntt);
    notes *n = new notes(ntt.name,&hashNotes,this);
    n->show();// 使用 show()显示非模态窗口 而不是 exec()
    connect(n,&notes::sigClose,this,&MainWindow::sigClose);

}

void MainWindow::sigClose(){
    this->saveHash();
    this->hashInit();
}

void MainWindow::on_pushButton_2_clicked()
{
    this->hashInit();
}


void MainWindow::on_lineEdit_textChanged(const QString &arg1)
{
    model->clear();
    // 添加根节点
    QStandardItem *rootNode = new QStandardItem(title);
    model->appendRow(rootNode);
    // 使用迭代器遍历 QHash
    for (auto i = hashNotes.begin(); i != hashNotes.end(); ++i) {
        if(i.value().name == "_nt_")continue;
        if(i.value().name.contains(arg1) || i.value().content.contains(arg1)){
            QStandardItem *dirNode = new QStandardItem(i.value().name);
            rootNode->appendRow(dirNode);
        }
    }

    ui->treeView->setExpanded(rootNode->index(),true);
}

//设置托盘图标
void MainWindow::setTrayIcon(){
    // 设置托盘图标
    QString icon = "/opt/apps/com.gitee.xinghuo.note/icon/note.png";
    trayIcon->setIcon(QIcon(icon));
    // 设置托盘图标工具提示
    trayIcon->setToolTip(title);
    // 创建上下文菜单
    QMenu *trayIconMenu = new QMenu(this);
    QAction *quitAction = trayIconMenu->addAction("退出");

    // 连接信号和槽
    connect(quitAction, &QAction::triggered, qApp,QCoreApplication::exit);
    connect(trayIcon, &QSystemTrayIcon::activated, this,&MainWindow::onTrayIconActivated);
    trayIcon->setContextMenu(trayIconMenu);
    trayIcon->show();
}

void MainWindow::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason) {
    if (reason == QSystemTrayIcon::Trigger) {
        // 当托盘图标被单击时，激活主窗口
        this->activateWindow();
    }
}

//设置背景色
void MainWindow::on_pushButton_3_clicked()
{
    // 显示颜色对话框
    QColorDialog dialog;
    backGroundColor = dialog.getColor();
    if(!backGroundColor.isValid())return;
    hashNotes["_nt_"].backGroundColor = backGroundColor.name();
    this->setStyleSheet("background-color:"+ backGroundColor.name() +
                        "; color: "+ fontColor.name() +";");
    this->saveHash();
}


void MainWindow::on_pushButton_4_clicked()
{
    // 显示颜色对话框
    QColorDialog dialog;
    fontColor = dialog.getColor();
    if(!fontColor.isValid())return;
    hashNotes["_nt_"].fontColor = fontColor.name();
    this->setStyleSheet("background-color:"+ backGroundColor.name() +
                        "; color: "+ fontColor.name() +";");
    this->saveHash();
}

/**
 * 同步功能
**/
void MainWindow::on_pushButton_5_clicked()
{
    sync *s = new sync(&hashNotes,this);
    s->setModal(true);
    s->show(); // 使用 show()显示非模态窗口 而不是 exec()
    connect(s,&sync::sigClose,this,&MainWindow::sigClose);
    connect(s,&sync::sigHashInit,this,&MainWindow::hashInit);
}

//海涛蓝
void MainWindow::on_pushButton_6_clicked()
{
    hashNotes["_nt_"].backGroundColor = "#15559a";
    hashNotes["_nt_"].fontColor = "#fff";
    this->setStyleSheet("background-color:"+ backGroundColor.name() +
                        "; color: "+ fontColor.name() +";");
    this->saveHash();
    this->hashInit();
}

//满天星紫
void MainWindow::on_pushButton_7_clicked()
{
    hashNotes["_nt_"].backGroundColor = "#2e317c";
    hashNotes["_nt_"].fontColor = "#fff";
    this->setStyleSheet("background-color:"+ backGroundColor.name() +
                        "; color: "+ fontColor.name() +";");
    this->saveHash();
    this->hashInit();
}

//荷叶绿
void MainWindow::on_pushButton_8_clicked()
{
    hashNotes["_nt_"].backGroundColor = "#1a6840";
    hashNotes["_nt_"].fontColor = "#fff";
    this->setStyleSheet("background-color:"+ backGroundColor.name() +
                        "; color: "+ fontColor.name() +";");
    this->saveHash();
    this->hashInit();
}

//玉红
void MainWindow::on_pushButton_9_clicked()
{
    hashNotes["_nt_"].backGroundColor = "#c04851";
    hashNotes["_nt_"].fontColor = "#fff";
    this->setStyleSheet("background-color:"+ backGroundColor.name() +
                        "; color: "+ fontColor.name() +";");
    this->saveHash();
    this->hashInit();
}

//星标事项颜色
void MainWindow::on_pushButton_10_clicked()
{
    // 显示颜色对话框
    QColorDialog dialog;
    startFontColor = dialog.getColor();
    if(!startFontColor.isValid())return;
    hashNotes["_nt_"].startFontColor = startFontColor.name();
    this->saveHash();
    this->hashInit();
}

